<template>
  <div class="slider" ref="slider">
    <div class="slider-group" ref="sliderGroup">
      <slot></slot>
    </div>
    <div class="dots">
      <div class="dot-wrapper" v-for="(item, index) in dots">
        <span class="dot" :class="{active: currentPageIndex === index }"></span>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import BScroll from "better-scroll";
import { addClass } from "common/js/dom";

export default {
  name: "Slider",
  props: {
    loop: {
      type: Boolean,
      default: true
    },
    autoPlay: {
      type: Boolean,
      default: true
    },
    interval: {
      type: Number,
      default: 4000
    }
  },
  data() {
    return {
      dots: [],
      currentPageIndex: 0
    };
  },

  mounted() {
    // 保证 DOM 成功渲染  也可以用nextTick  浏览器刷新 17ms 后
    setTimeout(() => {
      this._setSliderWidth();
      this._initDots();
      this._initSlider();
      if (this.autoPlay) {
        this._play();
      }
    }, 20);

    window.addEventListener("resize", () => {
      if (!this.slider) return;
      this._setSliderWidth(true);
    });
  },

  methods: {
    _setSliderWidth(isResize) {
      // 获取子元素
      this.children = this.$refs.sliderGroup.children;

      let width = 0;
      let sliderWidth = this.$refs.slider.clientWidth; //  轮播宽度

      // 设置类名和宽度
      for (let i = 0; i < this.children.length; i++) {
        let child = this.children[i];
        addClass(child, "slider-item");
        child.style.width = sliderWidth + "px";
        width += sliderWidth;
      }

      // 若循环，则需增加两个宽度值   （应该是插件所要求的）
      if (this.loop && !isResize) {
        width += 2 * sliderWidth;
      }

      this.$refs.sliderGroup.style.width = width + "px";
    },
    _initDots() {
      this.dots = new Array(this.children.length);
    },
    _initSlider() {
      this.slider = new BScroll(this.$refs.slider, {
        scrollX: true,
        scrollY: false,
        momentum: false,
        //  版本更新写法
        snap: {
          loop: this.loop,
          threshold: 0.3,
          speed: 400
        }
      });
      //  上下滑动时，若从轮播图中滑动会触发，导致自动轮播失效
      // this.slider.on("scrollStart", () => {
      //   clearTimeout(this.autoTimer);
      // });
      this.slider.on("scrollEnd", () => {
        let pageIndex = this.slider.getCurrentPage().pageX;
        this.currentPageIndex = pageIndex;

        if (this.autoPlay) {
          clearTimeout(this.autoTimer);
          this._play();
        }
      });
    },
    _play() {
      this.autoTimer = setTimeout(() => {
        //  版本更新写法
        this.slider.next();
      }, this.interval);
    }
  },

  //  添加keep-alive后增加的生命期钩子，进入和离开
  activated() {
    if (this.autoPlay) {
      this._play()
    }
  },
  deactivated() {
    clearTimeout(this.autoTimer);
  },

  //  销毁时清除定时器
  destroyed() {
    clearTimeout(this.autoTimer);
  }
};
</script>

<style lang="stylus" scoped>
@import '~common/stylus/variable';

.slider {
  min-height: 1px;

  .slider-group {
    position: relative;
    white-space: nowrap;
    overflow: hidden;

    .slider-item {
      float: left;
      overflow: hidden;
      box-sizing: border-box;
      text-align: center;

      a {
        display: block;
        width: 100%;
        overflow: hidden;

        img {
          display: block;
          width: 100%;
        }
      }
    }
  }

  .dots {
    position: absolute;
    right: 0;
    left: 0;
    bottom: 12px;
    text-align: center;
    font-size: 0;

    .dot-wrapper {
      display: inline-block;
      text-align: center;
      width: 20px;
      height: 8px;

      .dot {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: $color-text-l;
        transition: width 0.2s;

        &.active {
          width: 20px;
          border-radius: 5px;
          background: $color-text-ll;
        }
      }
    }
  }
}
</style>
